package com.bxl.netty.rpc.client.handler;

import com.bxl.netty.rpc.common.builder.ResponseMsgBuilder;
import com.bxl.netty.rpc.common.context.Context;
import com.bxl.netty.rpc.common.message.MsgResponseContent;
import com.bxl.netty.rpc.common.serialize.Serialize;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * <>
 *
 * @author baixl
 * @date 2021/2/23
 */
public class ClientMsgDecoder extends ByteToMessageDecoder {
    private final static int HEADER_LENGTH = 16;// header的长度
    private Context context;
    private Serialize serialize;

    public ClientMsgDecoder() {

    }

    public ClientMsgDecoder(Context context) {
        assert context == null;
        this.context = context;
        this.serialize = this.context.getSerialize();
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 长度不足，退出
        if (in.readableBytes() < HEADER_LENGTH) {
            return;
        }
        // 获取协议的版本
        int flag = in.readInt();
        // 获取消息长度
        long requestID = in.readLong();

        int length = in.readInt();
        if (in.readableBytes() < length) {
            in.setIndex(in.readerIndex() - HEADER_LENGTH, in.writerIndex());
            return;
        }
        // 获取SessionId
        byte[] content = new byte[length];
        in.readBytes(content);
        MsgResponseContent msgResponseContent = this.serialize.deserialize(content);
        out.add(ResponseMsgBuilder.createMsg(flag, requestID, msgResponseContent));
    }
}
